import 'dart:io';

import 'package:csv/csv.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sensor_backend/assets/color.dart';
import 'package:flutter_sensor_backend/component/niw.dart';
import 'package:flutter_sensor_backend/component/sensor_preview.dart';
import 'package:flutter_sensor_backend/page/user_preview/test_data.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'package:sensors_plus/sensors_plus.dart';
import 'package:toast/toast.dart';

class UserPreview extends StatefulWidget {
  const UserPreview({super.key});

  @override
  State<UserPreview> createState() => _UserPreviewState();
}

class _UserPreviewState extends State<UserPreview> {
  bool uploading = false;
  int count = 0;
  bool showRed = false;

  createCSVFile() async {
    if (uploading) return;
    setState(() {
      uploading = true;
    });
    List<List<dynamic>> rootAttendanceList = test_data;
    List<List<dynamic>> rows = [];
    List head = ["col_1", "col_2", "col_3", "col_4", "col_5", "col_6"];

    List<dynamic> row_header = [];
    for (var j = 0; j < head.length; j++) {
      row_header.add(head[j]);
    }
    rows.add(row_header);

    for (int i = 0; i < rootAttendanceList.length; i++) {
      List<dynamic> row = [];
      for (var j = 0; j < rootAttendanceList[i].length; j++) {
        row.add(rootAttendanceList[i][j]);
      }
      rows.add(row);
    }

    // print("rows =======$rows");
    Directory documentsDir = (await getApplicationDocumentsDirectory());
    // 创建ble文件夹
    Directory desDir = await Directory('${documentsDir.path}/ble').create();
    // print("desDir=${desDir.path}");
    String file = "${desDir.path}";
    File f = new File(file + "/myReport.csv");

    // 生成csv文件，csv文件路径：缓存目录下的 ble文件夹下
    String csv = const ListToCsvConverter().convert(rows);
    await f.writeAsString(csv);
    // print("生成csv文件路径=${f.path}");
    var request = http.MultipartRequest(
      'POST',
      Uri.parse('http://192.168.1.153:8080/upload'),
    );
    count++;
    request.files.add(
      await http.MultipartFile.fromBytes(
        "myfile",
        f.readAsBytesSync(),
        filename: "output_$count.csv",
      ),
    );

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
    } else {
      print(response.reasonPhrase);
    }
    test_data = [];
    uploading = false;
    Toast.show("采集第$count次成功！", gravity: Toast.center);
    collectIt = false;
    setState(() {
      showRed = false;
    });
  }

  getSingle() async {}

  bool collectIt = false;

  getSensor() async {
    int row_a = 0;
    int row_g = 0;
    int length = 200;
    List<double> tmp = [];
    accelerometerEvents.listen((event) {
      if (test_data.length == length && collectIt) {
        createCSVFile();
        return;
      }
      tmp = [];
      if (row_a == row_g && test_data.length < length) {
        tmp.add(event.x);
        tmp.add(event.y);
        tmp.add(event.z);
        row_a++;
      }
    });
    gyroscopeEvents.listen((event) {
      if (test_data.length == length && collectIt) {
        createCSVFile();
        return;
      }
      if (row_g == row_a - 1 && test_data.length < length) {
        tmp.add(event.x);
        tmp.add(event.y);
        tmp.add(event.z);
        row_g++;
        if (tmp.length == 6) {
          test_data.add(tmp);
        }
      }
    });
  }

  @override
  void initState() {
    getSensor();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: showRed ? Colors.red : os_back,
      appBar: AppBar(
        foregroundColor: showRed ? Colors.white : os_black,
        backgroundColor: showRed ? Colors.red : os_back,
      ),
      body: ListView(
        children: [
          SensorPreview(),
          Container(height: 50),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              myInkWell(
                color: showRed ? os_white : os_color,
                tap: () {
                  test_data = [];
                  setState(() {
                    showRed = true;
                  });
                  collectIt = true;
                },
                radius: 200,
                widget: Container(
                  width: 200,
                  height: 200,
                  decoration: BoxDecoration(
                    // color: os_color,
                    borderRadius: BorderRadius.circular(100),
                  ),
                  child: Center(
                    child: Text(
                      "采集",
                      style: TextStyle(
                        color: showRed ? Colors.red : os_white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          // TextButton(
          //   onPressed: () {
          //     collectIt = true;
          //   },
          //   child: Text("采集一次"),
          // ),
        ],
      ),
    );
  }
}
